package xim

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 获取用户的设备ID
//
//	uid	用户ID
//	mac	用户设备MAC【H5端获取不到MAC，建议使用{"h5mac":"android/ios/win/linux...:safari/firefox....:720...<屏幕宽度>"}】
func GetDervice(uid uint, mac map[string]string) (*ImUserDervice, error) {
	if len(mac) == 0 {
		return nil, xerror.New("设备MAC不允许为空")
	}
	if uid == 0 {
		return nil, xerror.New("用户ID不存在")
	}
	der := ImUserDervice{}
	macs := []string{}
	// 缓存判定
	for _, v := range mac {
		if v == "" {
			continue
		}
		macs = append(macs, v)
		cache_key := xcache.Key("xim.get.dervice", v)
		if xcache.Exists(cache_key) {
			if err := xcache.GetStruct(cache_key, &der); err == nil {
				return &der, nil
			}
		}
	}
	if len(macs) == 0 {
		return nil, xerror.New("设备MAC不允许为空")
	}
	// 从数据库中进行获取
	ders := []ImUserDerviceMac{}
	err := _default.DB.Table(_default.UserDerviceMacTable).
		Where("user_id", uid).
		Where("is_deleted", 0).
		Where("`mac` IN ?", macs).
		Find(&ders).
		Error
	if err != nil {
		return nil, xlog.AE("用户IM设备信息查询错误", err)
	}
	for _, v := range ders {
		for kk, vv := range mac {
			if vv == v.Mac {
				// 查询到该MAC了，就清理掉该MAC
				delete(mac, kk)
			}
		}
	}
	dervice_ids := []uint{}
	for i := 0; i < len(ders); i++ {
		dervice_ids = append(dervice_ids, ders[i].DerviceId)
	}
	if len(dervice_ids) == 0 {
		return nil, xerror.New("未检索到相应设备，先注册该设备再行查询")
	}
	// 查询对应的设备信息
	err = _default.DB.Table(_default.UserDerviceTable).
		Where("id IN ?", dervice_ids).
		Where("user_id", uid).
		Where("is_deleted", 0).
		Order("id ASC").
		Limit(1).
		Find(&der).
		Error
	if err != nil {
		return nil, xlog.AE("设备信息查询错误", err)
	}
	if der.Id == 0 {
		return nil, xerror.New("检索设备数据错误")
	}
	// 写入缓存
	for _, v := range macs {
		xcache.SetStruct(xcache.Key("xim.get.dervice", v), der)
	}
	return &der, nil
}

// 创建设备Mac地址
//
//	did	设备ID
//	uid	所属用户
//	mac	MAC地址
func create_mac(did, uid uint, mac map[string]string) {
	// 将未注入的mac地址重新注入进去
	if len(mac) > 0 {
		for k, v := range mac {
			m := ImUserDerviceMac{
				DerviceId: did,
				UserId:    uid,
				CreatedAt: time.Now().Format(time.DateTime),
				Mac:       v,
				MacName:   k,
			}
			_default.DB.Table(_default.UserDerviceMacTable).Create(&m)
		}
		go InitUserChat(uid)
	}
}
